package com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis

import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisDXT.AnalysisFragmentDxt
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisGCT.AnalysisFragmentGct
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisJDT.AnalysisFragmentJdt
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisPPT.AnalysisFragmentPpt
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisTKT.AnalysisFragmentTkt
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisWXXZ.AnalysisFragmentWxxz
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisXZT.AnalysisFragmentXzt
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisYDPP.AnalysisFragmentYdpp
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisZHT.AnalysisFragmentZht
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisZW.AnalysisFragmentZw
import android.app.Activity
import android.content.Intent
import android.text.Html
import android.text.TextPaint
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseActivity
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkDialog.ShowDialogTools
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.JumpActivityHelp
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.LancooMethod
import com.lancoo.znbkxx.teacher.aibkTestCoach.kBase.KBaseFragmentPagerAdapter
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.entity.PaperPerAnalysisInfor
import com.lancoo.znbkxx.teacher.aibkTestCoach.networkRequest.viewModel.MarkViewModel
import com.lancoo.znbkxx.teacher.aibkTestCoach.paperToPersonalAnalysis.aibkAnalysisFHXZ.AnalysisFragmentFhxz
import com.lancoo.znbkxx.teacher.utils.DensityUtils
import kotlinx.android.synthetic.main.aibk_activity_paper_analysis.*
import kotlinx.android.synthetic.main.aibk_activity_paper_analysis.BtnBack
import kotlinx.android.synthetic.main.aibk_activity_paper_analysis.LlToolsView
import kotlinx.android.synthetic.main.aibk_activity_paper_analysis.TvPaperName
import kotlinx.android.synthetic.main.aibk_activity_paper_analysis.TvQuesInfor
import kotlinx.android.synthetic.main.aibk_activity_paper_evaluation.*
import org.koin.androidx.viewmodel.ext.android.viewModel

/*
* add by 王国龙
* Time 2020.09.11
* 试卷分析试题加载页面
* */
class AibkPaperAnalysisActivity : KBaseActivity(), View.OnClickListener {

    companion object {
        private var paperPerAnalysisInfor: PaperPerAnalysisInfor? = null
        fun launch(activity: Activity, paperId: String, paperName: String, setName: String, sortIndex: String, paperPerAnalysisInforX: PaperPerAnalysisInfor) {
            val intent = Intent(activity, AibkPaperAnalysisActivity::class.java)
            intent.putExtra("PaperID", paperId)
            intent.putExtra("PaperName", paperName)
            intent.putExtra("SetName", setName)
            intent.putExtra("SortIndex", sortIndex)
            paperPerAnalysisInfor = paperPerAnalysisInforX
            activity.startActivityForResult(intent, 1)
        }
    }

    private var quesScoreInfor = ""
    private var isFullOneLine = false
    private val mViewModel: MarkViewModel by viewModel()
    private var typeListPosition = 0
    private var quesPosition = 0
    private var vpPosition = 0
    private var fragmentList: MutableList<Fragment>? = ArrayList()

    override fun setLayout(): Int {
        return R.layout.aibk_activity_paper_analysis
    }

    override fun initView() {
        BtnBack.setOnClickListener(this)
        BtnZsd.setOnClickListener(this)
        TvQuesInfor.setOnClickListener(this)
    }

    //初始化显示试卷概要信息
    override fun initData() {
//        paperPerAnalysisInfor = intent.getParcelableExtra<paperPerAnalysisInfor>("paperPerAnalysisInfor")
//        Log.e("AibkPaperAnalysis", "=======State===========" + paperPerAnalysisInfor!!.TypeList.size)
        val sortIndex = intent.getStringExtra("SortIndex")
        LoadPaperView(paperPerAnalysisInfor!!, sortIndex)
    }

    //加载试卷UI
    private fun LoadPaperView(paperPerAnalysisInfor: PaperPerAnalysisInfor, sortIndex: String) {
        //显示试卷名称以及答题卡按钮
        LlToolsView.visibility = View.VISIBLE
        TvPaperName.visibility = View.VISIBLE
        val paperName = intent.getStringExtra("PaperName")
        val setName = intent.getStringExtra("SetName")
        if(setName.isEmpty()){
            TvPaperName.text = paperName+"的详情"
        }else {
            TvPaperName.text = "$paperName($setName)的详情"
        }
        TvQuesInfor.visibility = View.VISIBLE

        val index_i = AnalysisInforIndexHelp.SortIndex_return_IndexA(paperPerAnalysisInfor, sortIndex)
        val index_j = AnalysisInforIndexHelp.SortIndex_return_IndexB(paperPerAnalysisInfor, sortIndex)
        //加载试题,显示试卷作答情况
        fragmentList?.clear()
        var typeListSize = paperPerAnalysisInfor.TypeList.size
        for (i in 0 until typeListSize) {
            var typeNo = paperPerAnalysisInfor.TypeList[i].TypeNo
            var quesListSize = paperPerAnalysisInfor.TypeList[i].QuesList.size
            for (j in 0 until quesListSize) {
                if (typeNo == "A") {
                    val mFragment = AnalysisFragmentDxt(this, paperPerAnalysisInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "C") {
                    val mFragment = AnalysisFragmentWxxz(this, paperPerAnalysisInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                    if (index_i == i && index_j == j) {
                        mFragment.fragmentJumpToSortIndex(sortIndex)
                    }
                } else if (typeNo == "L" ||typeNo == "E" || typeNo == "F" || typeNo == "D") {//听力选择，听力判断，阅读选择
                    val mFragment = AnalysisFragmentXzt(this, paperPerAnalysisInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                    if (index_i == i && index_j == j) {
                        mFragment.fragmentJumpToSortIndex(sortIndex)
                    }
                } else if (typeNo == "k") {
                    val mFragment = AnalysisFragmentZht(this, paperPerAnalysisInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                    if (index_i == i && index_j == j) {
                        mFragment.fragmentJumpToSortIndex(sortIndex)
                    }
                } else if (typeNo == "H") {
                    val mFragment = AnalysisFragmentFhxz(this, paperPerAnalysisInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                    if (index_i == i && index_j == j) {
                        mFragment.fragmentJumpToSortIndex(sortIndex)
                    }
                }  else if (typeNo == "f") {
                    val mFragment = AnalysisFragmentZw(this, paperPerAnalysisInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "N" || typeNo == "S") { //N:普通填空题  S：听力填空题
                    val mFragment = AnalysisFragmentTkt(this, paperPerAnalysisInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                    if (index_i == i && index_j == j) {
                        mFragment.fragmentJumpToSortIndex(sortIndex)
                    }
                } else if (typeNo == "Q" || typeNo == "b" || typeNo == "d"
                        || typeNo == "X" || typeNo == "g" || typeNo == "V"
                        || typeNo == "G") {//Q:阅读填空,X:阅读简答,G:听力简答,
                    val mFragment = AnalysisFragmentJdt(this, paperPerAnalysisInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                    if (index_i == i && index_j == j) {
                        mFragment.fragmentJumpToSortIndex(sortIndex)
                    }
                } else if (typeNo == "x" || typeNo == "m") {//x:听力匹配,m:普通匹配题
                    val mFragment = AnalysisFragmentPpt(this, paperPerAnalysisInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                    if (index_i == i && index_j == j) {
                        mFragment.fragmentJumpToSortIndex(sortIndex)
                    }
                } else if (typeNo == "U") {
                    val mFragment = AnalysisFragmentGct(this, paperPerAnalysisInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                } else if (typeNo == "P") {
                    val mFragment = AnalysisFragmentYdpp(this, paperPerAnalysisInfor, i, j)
                    (fragmentList as ArrayList<Fragment>).add(mFragment)
                }
            }
        }

        val mAdapter = KBaseFragmentPagerAdapter(supportFragmentManager, fragmentList as ArrayList<Fragment>)
        VpAnalysis.adapter = mAdapter

        //处理viewpager滑动事件
        VpAnalysis.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                vpPosition = position
                showQuesTitleInfor(paperPerAnalysisInfor, position)
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })

        vpPosition = AnalysisInforIndexHelp.SortIndex_return_ParentVpPosition(paperPerAnalysisInfor, sortIndex)
        VpAnalysis.setCurrentItem(vpPosition, true)
        showQuesTitleInfor(paperPerAnalysisInfor, vpPosition)
    }

    //显示切换后试题信息
    private fun showQuesTitleInfor(paperPerAnalysisInfor: PaperPerAnalysisInfor, vpPosition: Int) {
        typeListPosition = AnalysisInforIndexHelp.ParentVpIndex_return_TypeListPosition(paperPerAnalysisInfor, vpPosition)
        quesPosition = AnalysisInforIndexHelp.ParentVpIndex_return_QuesListPosition(paperPerAnalysisInfor, vpPosition)
        val typeIndex = paperPerAnalysisInfor.TypeList[typeListPosition].TypeIndex
        val strTypeIndex = LancooMethod.numberToChinese(typeIndex)
        var genreName = paperPerAnalysisInfor.TypeList[typeListPosition].GenreName
        val typeName = paperPerAnalysisInfor.TypeList[typeListPosition].TypeName
        if (genreName.isEmpty()) {
            genreName = typeName
        }

        /******************************************************************************************/
        var totalChildQuesSize = 0
        var totalChildQuesScore = 0.0
        val quesListSize = paperPerAnalysisInfor.TypeList[typeListPosition].QuesList.size
        for (i in 0 until quesListSize) {
            val sortIndexListSize = paperPerAnalysisInfor.TypeList[typeListPosition].QuesList[i].SortIndexList.size
            totalChildQuesSize += sortIndexListSize

            for (j in 0 until sortIndexListSize) {
                val score = paperPerAnalysisInfor.TypeList[typeListPosition].QuesList[i].SortIndexList[j].Score
                totalChildQuesScore += score
            }
        }

        var isAverage = true
        val averageScore = LancooMethod.getCorrectRateInt(totalChildQuesScore, totalChildQuesSize)
        outLoop@ for (i in 0 until quesListSize) {
            val sortIndexListSize = paperPerAnalysisInfor.TypeList[typeListPosition].QuesList[i].SortIndexList.size
            for (j in 0 until sortIndexListSize) {
                val score = paperPerAnalysisInfor.TypeList[typeListPosition].QuesList[i].SortIndexList[j].Score
                if (score != averageScore) {
                    isAverage = false
                    break@outLoop
                }
            }
        }

            if (isAverage) {
                isFullOneLine = false
                TvQuesInfor.text = Html.fromHtml(resources.getString(R.string.aibk_practice_ques_infor_short,
                        strTypeIndex, genreName, quesListSize,totalChildQuesSize, averageScore.toString()))
            } else {
                isFullOneLine = true
                var childScoreAll = ""
                val quesListSize = paperPerAnalysisInfor.TypeList[typeListPosition].QuesList.size
                for (x in 0 until quesListSize) {
                    val sortIndexListSize = paperPerAnalysisInfor.TypeList[typeListPosition].QuesList[x].SortIndexList.size
                    for (y in 0 until sortIndexListSize) {
                        val sortIndex = paperPerAnalysisInfor.TypeList[typeListPosition].QuesList[x].SortIndexList[y].SortIndex
                        val score = paperPerAnalysisInfor.TypeList[typeListPosition].QuesList[x].SortIndexList[y].Score
                        val childScore = resources.getString(R.string.aibk_single_ques_infor, sortIndex, score.toString())
                        if (childScoreAll.isEmpty()) {
                            childScoreAll = childScore
                        } else {
                            childScoreAll = "$childScoreAll,$childScore"
                        }
                    }
                }
                TvQuesInfor.text = Html.fromHtml(resources.getString(R.string.aibk_practice_ques_infor_long,
                        strTypeIndex, genreName,quesListSize, totalChildQuesSize, childScoreAll))
            }
        /******************************************************************************************/
    }

    //界面点击事件
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.BtnBack -> {
                toolPauseAudio()
                backToAnswerSheetActivity()
            }

            R.id.BtnZsd -> {
                toolPauseAudio()
                JumpActivityHelp.paperAnalysisJumpToKnowledgePointActivity(this, paperPerAnalysisInfor!!,typeListPosition,quesPosition)
            }
            R.id.TvQuesInfor ->{
                quesScoreInfor =  TvQuesInfor.text.toString()
//                if(isFullOneLine) {
//                    ShowDialogTools.showQuesScoreInofrDialog(this, quesScoreInfor)
//                }
                val mTextPaint: TextPaint = TvQuesInfor.paint
                mTextPaint.textSize = TvQuesInfor.textSize
                val mTextViewWidth = mTextPaint.measureText(quesScoreInfor).toInt()
                val mTvQuesInforWidth = TvQuesInfor.width - DensityUtils.dp2px(this,20f)
                if (mTextViewWidth > mTvQuesInforWidth) { //超出一行
                    ShowDialogTools.showQuesScoreInofrDialog(this, quesScoreInfor)
                }
            }
        }
    }

    //响应系统返回事件
    override fun onBackPressed() {
        super.onBackPressed()
        backToAnswerSheetActivity()
    }

    //返回操作，并将需要的信息传递给上一个界面
    private fun backToAnswerSheetActivity() {
        val intent = Intent(this@AibkPaperAnalysisActivity, AibkAnalysisAnswerSheetActivity::class.java)
        intent.putExtra("TypeListPosition", typeListPosition)
        setResult(100, intent)
        finish()
    }

    //暂停一切音频播放
    private fun toolPauseAudio() {
        val typeNo = paperPerAnalysisInfor!!.TypeList[typeListPosition].TypeNo
        if (typeNo == "x") {//x:听力匹配
            val fragment = fragmentList!![vpPosition] as AnalysisFragmentPpt
            fragment.pauseAudio()
            fragment.pauseChildAudio()
            fragment.audioTrackerStop()
        } else if (typeNo == "L" ||typeNo == "E" || typeNo == "F") {//听力选择，听力判断
            val fragment = fragmentList!![vpPosition] as AnalysisFragmentXzt
            fragment.pauseAudio()
            fragment.pauseChildAudio()
            fragment.audioTrackerStop()
        } else if (typeNo == "G") {//G:听力简答,
            val fragment = fragmentList!![vpPosition] as AnalysisFragmentJdt
            fragment.pauseAudio()
            fragment.pauseChildAudio()
            fragment.audioTrackerStop()
        } else if (typeNo == "S") { // S：听力填空题
            val fragment = fragmentList!![vpPosition] as AnalysisFragmentTkt
            fragment.pauseAudio()
            fragment.pauseChildAudio()
            fragment.audioTrackerStop()
        } else if (typeNo == "f") {
            val fragment = fragmentList!![vpPosition] as AnalysisFragmentZw
            fragment.pauseAudio()
            fragment.pauseChildAudio()
            fragment.audioTrackerStop()
        }else if (typeNo == "H") {
            val fragment = fragmentList!![vpPosition] as AnalysisFragmentFhxz
            fragment.pauseAudio()
            fragment.pauseChildAudio()
            fragment.audioTrackerStop()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 0) {
            if (resultCode == 101) {
                val noteId = data?.getStringExtra("NoteID")
                val indexA = AnalysisInforIndexHelp.ParentVpIndex_return_TypeListPosition(paperPerAnalysisInfor!!, vpPosition)
                val indexB = AnalysisInforIndexHelp.ParentVpIndex_return_QuesListPosition(paperPerAnalysisInfor!!, vpPosition)
                paperPerAnalysisInfor!!.TypeList[indexA].QuesList[indexB].NoteID = noteId
            }
        }
    }

}